<template>
  <div>
    <Card _Title="订单详情" :_Size="16"></Card>
    <a-card _Title=""  bordered :body-style="bodyStyle"
            v-if="orderDetails && orderDetails.allowOperationVO && (orderDetails.allowOperationVO.pay || orderDetails.allowOperationVO.rog || orderDetails.allowOperationVO.cancel)">
      <a-button status="success" type="primary" size="small" class="mr_10" @click="goPay(orderDetails.order.tradeSn)" v-if="orderDetails.allowOperationVO.pay">去支付</a-button>
      <a-button status="warning" type="outline" size="small" class="mr_10" @click="received(orderDetails.order.sn)" v-if="orderDetails.allowOperationVO.rog">确认收货</a-button>
      <a-button status="danger" type="primary" size="small" class="mr_10" @click="handleCancelOrder(orderDetails.order.tradeSn)" v-if="orderDetails.allowOperationVO.cancel">取消订单</a-button>
    </a-card>
    <!--自提订单核验码-->
    <div class="verificationCode" v-if="orderDetails.order && orderDetails.order.verificationCode">核验码：<span>{{ orderDetails.order.verificationCode }}</span></div>
    <!--订单状态-->
    <div v-if="orderDetails && orderDetails.order">
      <div class="global-color fontsize-18 mt_20">{{ orderDetails.orderStatusValue }}</div>
      <!--未付款时倒计时-->
      <div v-if="orderDetails.orderStatusValue=='未付款'" class="left-tips-count-down" style="color: #e4393c;">
      <count-down :countdown="data.endTime" :is-stop="data.isStart" format="HH:mm:ss" finishedText="订单已超时取消" @finish="onFinish">
        <!--<template #prefix>There's only </template>-->
         <!--<template #finish>{{data.endText}}</template>-->
        <!--<template #suffix> left for the end.</template>-->
      </count-down>
      </div>
      <div class="flex mt_10" style="justify-content: space-between;">
        <div class="light-text-color">订单号：{{orderDetails.order.sn}}</div>
        <div class="operation-time light-text-color">操作时间：{{ orderDetails.order.updateTime || orderDetails.order.createTime }}</div>
      </div>
    </div>
    <!--订单流程-->
    <div class="steps-box mt_20 mb_20">
      <a-steps small direction="vertical" :current="data.progressList.length+1">
        <a-step :description="progress.createTime" v-for="(progress, index) in data.progressList" :key="index">{{progress.message}}</a-step>
      </a-steps>
    </div>
    <!--收货人信息-->
    <div class="order-card pt_10 pb_10 pl_20" v-if="orderDetails.order && orderDetails.order.deliveryMethod === 'LOGISTICS' && orderDetails.order.orderType !== 'VIRTUAL'">
      <h3 class="text-color">收货人信息</h3>
      <p class="light-text-color">收货人：{{ orderDetails.order.consigneeName }}</p>
      <p class="light-text-color">手机号码：{{ secrecyMobile(orderDetails.order.consigneeMobile) }}</p>
      <p class="light-text-color">收货地址：{{ unitAddress(orderDetails.order.consigneeAddressPath) }} {{ orderDetails.order.consigneeDetail }}</p>
    </div>
    <!--自提点信息-->
    <div class="order-card pt_10 pb_10 pl_20" v-if="orderDetails.order && orderDetails.order.deliveryMethod === 'SELF_PICK_UP'">
      <h3 class="text-color">自提点信息</h3>
      <p class="light-text-color">自提点名称：{{ orderDetails.order.storeAddressPath }}</p>
      <p class="light-text-color">联系方式：{{ orderDetails.order.storeAddressMobile }}</p>
    </div>
    <!--付款信息-->
    <div class="order-card pt_10 pb_10 pl_20">
      <h3 class="text-color">付款信息</h3>
      <p class="light-text-color">支付方式：{{ orderDetails.paymentMethodValue }}</p>
      <p class="light-text-color">付款状态：{{ orderDetails.payStatusValue }}</p>
    </div>
    <!--查看物流-->
    <div v-if="orderDetails && orderDetails.allowOperationVO && (orderDetails.allowOperationVO.showLogistics || data.orderPackage.length > 0 || data.logistics)" class="mt_10">
      <a-button status="warning" type="outline" size="mini" class="mr_10" @click="logisticsList()">查看物流</a-button>
    </div>
    <!--配送信息-->
    <div class="order-card pt_10 pb_10 pl_20" v-else-if="orderDetails && orderDetails.order && !orderDetails.order.verificationCode && orderDetails.order.orderType !== 'VIRTUAL'">
      <h3 class="text-color">配送信息</h3>
      <p class="light-text-color">配送方式：{{ orderDetails.deliveryMethodValue }}</p>
      <p class="light-text-color" v-if="orderDetails.order.deliveryMethod === 'LOGISTICS'">配送状态：{{ orderDetails.deliverStatusValue }}</p>
      <p v-if="data.logistics">物流信息：{{ data.logistics.shipper || "暂无物流信息" }}</p>
      <p v-if="data.logistics">
        物流单号：{{ data.logistics.logisticCode || "暂无物流单号" }}
      </p>
      <div class="div-express-log" v-if="data.logistics">
        <div class="express-log">
          <p>订单日志：</p>
          <div v-for="(item, index) in data.logistics.traces" :key="index">
            <span class="time">{{ item.AcceptTime }}</span>
            <span class="detail">{{ item.AcceptStation }}</span>
          </div>
        </div>
      </div>
    </div>
    <!--发票信息-->
    <div class="order-card pt_10 pb_10 pl_20" v-if="orderDetails && orderDetails.order && orderDetails.order.payStatus === 'PAID'">
      <h3 class="text-color">发票信息</h3>
      <template v-if="orderDetails.order.needReceipt && orderDetails.receipt">
        <p class="light-text-color">发票抬头：{{ orderDetails.receipt.receiptTitle }}</p>
        <p class="light-text-color">发票内容：{{ orderDetails.receipt.receiptContent }}</p>
        <p class="light-text-color" v-if="orderDetails.receipt.taxpayerId">纳税人识别号：{{ orderDetails.receipt.taxpayerId }}</p>
      </template>
      <div class="light-text-color" v-else>未开发票</div>
    </div>
    <!--促销赠送积分-->
    <div class="order-card pt_10 pb_10 pl_20" v-if="orderDetails && orderDetails.order && orderDetails.order.giftPoint">
      <h3 class="text-color">促销赠送积分：</h3>
      <p class="light-text-color">积分：+{{ orderDetails.order.giftPoint}}</p>
    </div>
    <!--订单商品-->
    <div class="goods" v-if="orderDetails && orderDetails.order">
      <div class="shop-name hover-pointer mt_20 mb_10"><span @click="goShopPage(orderDetails.order.storeId)">{{orderDetails.order.storeName}}</span></div>
      <div>
        <div class="goods-header flex" style="background-color: #f3f4f5;">
          <div style="width:40%;">商品</div>
          <div style="width:20%;">货号</div>
          <div style="width:10%;">单价</div>
          <div style="width:10%;">数量</div>
          <div style="width:10%;">小计</div>
          <div style="width:10%;">操作</div>
        </div>
        <div class="goods-body flex" v-for="(goods, goodsIndex) in orderDetails.orderItems" :key="goodsIndex">
          <div style="width:40%;">
            <div class="flex goods-detail">
              <a-image width="60" height="60" :src="goods.image" @click="goodsDetail(goods.skuId, goods.goodsId)"/>
              <div @click="goodsDetail(goods.skuId, goods.goodsId)" class="hover-color ml_10">{{ goods.goodsName }}</div>
            </div>
          </div>
          <div style="width:20%;">{{ goods.id }}</div>
          <div style="width:10%;">{{ unitPrice(goods.goodsPrice, "￥") }}</div>
          <div style="width:10%;">{{ goods.num }}</div>
          <div style="width:10%;">{{ unitPrice(goods.goodsPrice*goods.num, "￥") }}</div>
          <div style="width:10%;">
            <a-button  v-if="goods.afterSaleStatus.includes('NOT_APPLIED') ||goods.afterSaleStatus.includes('PART_AFTER_SALE')"
                       @click="applyAfterSale(goods.sn)" size="mini" type="primary" status="danger" class="mb_10">申请售后</a-button>
            <a-button  v-if="goods.commentStatus == 'UNFINISHED'"
                       @click="comment(orderDetails.order.sn, goodsIndex)" size="mini" type="primary" status="success" class="mb_10">评价</a-button>
            <a-button v-if="goods.complainStatus == 'NO_APPLY'"
                      @click="complain(orderDetails.order.sn, goodsIndex)" size="mini" type="primary" status="warning" class="mb_10">投诉</a-button>
          </div>
        </div>
      </div>
    </div>
    <!--订单价格-->
    <div class="order-price mt_20 mb_20">
      <div v-if="orderDetails && orderDetails.order && orderDetails.order.goodsNum">
        <span>商品件数：</span><span>{{ orderDetails.order.goodsNum }}件</span>
      </div>
      <div v-if="orderDetails && orderDetails.order && orderDetails.order.goodsPrice">
        <span>商品总价：</span><span>{{unitPrice(orderDetails.order.goodsPrice, "￥") }}</span>
      </div>
      <div v-if="orderDetails && orderDetails.order && orderDetails.order.freightPrice">
        <span>运费：</span><span>+{{unitPrice(orderDetails.order.freightPrice, "￥") }}</span>
      </div>
      <div v-if="orderDetails && orderDetails.order && orderDetails.order.priceDetailDTO.payPoint">
        <span>积分：</span><span>- {{ orderDetails.order.priceDetailDTO.payPoint  }}</span>
      </div>
      <div v-if="orderDetails && orderDetails.order && orderDetails.order.priceDetailDTO.couponPrice">
        <span>优惠券：</span><span>-{{unitPrice(orderDetails.order.priceDetailDTO.couponPrice, "￥")}}</span>
      </div>
      <div v-if="orderDetails && orderDetails.order && orderDetails.order.discountPrice">
        <span>活动优惠：</span><span>-{{unitPrice(orderDetails.order.discountPrice, "￥") }}</span>
      </div>
      <div v-if="orderDetails && orderDetails.order && orderDetails.order.flowPrice">
        <span>应付金额：</span><span class="actrual-price">{{unitPrice(orderDetails.order.flowPrice, "￥")}}</span>
      </div>
    </div>


    <!--取消订单modal-->
    <a-modal v-model:visible="data.cancelAvail" width="600px">
      <template #title>请选择取消订单原因</template>
      <div class="">
        <a-radio-group v-model="data.cancelParams.reason" type="button" class="mb_10">
          <a-radio :value="item.reason"  v-for="item in data.cancelReason" :key="item.id">{{ item.reason }}</a-radio>
        </a-radio-group>
      </div>
      <template #footer>
        <a-button @click="data.cancelAvail = false">取消</a-button>
        <a-button @click="sureCancel" status="danger" type="primary">确定</a-button>
      </template>
    </a-modal>
    <!--查询物流modal-->
    <a-modal v-model:visible="data.logisticsModal" width="600px">
      <template #title>查询物流</template>
      <div class="">
        <div class="layui-layer-wrap">
          <div class="flex"><div>订单号：</div><div v-if="orderDetails.order">{{ orderDetails.order.sn }}</div></div>
        </div>
        <div v-if="data.packageTraceList.length > 0" v-for="(packageItem, packageIndex) in data.packageTraceList" :key="packageIndex">
          <div class="layui-layer-wrap">
            <div class="flex"><div>物流公司：</div><div>{{ packageItem.logisticsName }}</div></div>
            <div class="flex"><div>快递单号：</div><div>{{ packageItem.logisticsNo }}</div></div>
            <div class="div-express-log fontsize-14">
              <ul class="express-log express-log-name">
                <li v-for="(item, index) in packageItem.orderPackageItemList" :key="index">
                  <span class="time" style="width: 50%;"><span>商品名称：</span><span>{{ item.goodsName }}</span></span>
                  <span class="time" style="width: 30%;"><span>发货时间：</span><span>{{ item.logisticsTime }}</span></span>
                  <span class="time" style="width: 20%;"><span>发货数量：</span><span>{{ item.deliverNumber }}</span></span>
                </li>
              </ul>
              <div class="div-express-log" style="overflow: hidden;">
                <ul class="express-log" v-if="packageItem.traces && packageItem.traces.traces">
                  <li v-for="(item, index) in packageItem.traces.traces" :key="index">
                    <span class="time">{{ item.AcceptTime || item.acceptTime }}</span>
                    <span class="detail">{{ item.AcceptStation || item.remark }}</span>
                  </li>
                </ul>
                <ul class="express-log" v-else><li>暂无物流信息</li></ul>
              </div>
            </div>
          </div>
        </div>
        <template v-if = "data.packageTraceList.length === 0 && data.logistics">
          <div class="layui-layer-wrap">
            <div class="flex"><div>物流公司：</div><div>{{ data.logistics.shipper }}</div></div>
            <div class="flex"><div>快递单号：</div><div>{{ data.logistics.logisticCode }}</div></div>
            <div class="div-express-log">
              <ul class="express-log" v-if="data.logistics && data.logistics.traces">
                <li v-for="(item, index) in data.logistics.traces" :key="index">
                  <span class="time">{{ item.AcceptTime }}</span>
                  <span class="detail">{{ item.AcceptStation }}</span>
                </li>
              </ul>
              <ul class="express-log" v-else><li>暂无物流信息</li></ul>
            </div>
          </div>
        </template>
      </div>
      <template #footer>
        <a-button @click="data.logisticsModal = false">取消</a-button>
      </template>
    </a-modal>


  </div>
</template>

<script setup lang="ts">
  import { useRouter, useRoute } from 'vue-router';
  import { ref, onMounted } from 'vue';
  import { unitPrice } from '@/utils/filters';
  import { orderDetail, getTraces, getPackage, sureReceived, cancelOrder } from "@/api/order";
  import { secrecyMobile, unitAddress } from '@/utils/filters';
  import { Message, Modal } from '@arco-design/web-vue';
  import { afterSaleReason } from "@/api/member";

  const router = useRouter();
  const route = useRoute();
  interface formInterface {
    orderPackage: any,
    packageTraceList: any,
    logisticsModal: boolean,
    progressList: any,
    logistics: any,
    cancelParams: {
      orderSn: string,
      tradeSn: string,
      reason: string,
    },
    cancelAvail: boolean, // 取消订单modal控制
    cancelReason: Array<any>, // 取消订单原因
    startTime: any, // 开始时间（时间戳）
    endTime: any, // 完成的时间（时间戳）
    endText: string, // 倒计时完成的提示文本
    isStart: boolean, // 控制倒计时开始的时机（异步请求完成开启）（如果要主动停止倒计时,对组件的props.isStop设置为true进行了,恢复计时设置为false）
  }
  // 数据集
  const data = ref<formInterface>({
    orderPackage: [],
    packageTraceList: [],
    logisticsModal: false,
    progressList: [], // 订单流程
    logistics: "", // 物流数据
    cancelParams: {
      // 取消售后参数
      orderSn: "",
      tradeSn: "",
      reason: "",
    },
    cancelAvail: false, // 取消订单modal控制
    cancelReason: [], // 取消订单原因
    startTime: new Date().getTime(), // 开始时间（时间戳）
    endTime: 0, // 完成的时间（时间戳）
    endText: '订单已超时取消', // 倒计时完成的提示文本
    isStart: false, // 控制倒计时开始的时机（异步请求完成开启）（如果要主动停止倒计时,对组件的props.isStop设置为true进行了,恢复计时设置为false）
  });
  const bodyStyle = ref({border: 'none'});
  // 订单详情数据
  const orderDetails = ref<any>({});

  const getOrderPackage = (sn: any) => {
    getPackage(sn).then(res => {
      if (res.data.success) {
        data.value.orderPackage = res.data.result;
      }
    })
  };
  const traces = () => {
    // 物流信息
    getTraces(route.query.sn).then((res) => {
      if (res.data.success) {
        data.value.logistics = res.data.result;
      }
    });
  };
  // 获取订单详情
  const getDetail = () => {
    orderDetail(route.query.sn).then((res) => {
      if (res.data.success) {
        data.value.endTime = Date.parse(res.data.result.cancelOrderTime);
        orderDetails.value = res.data.result;
        data.value.isStart = true;
        data.value.progressList = res.data.result.orderLogs;
        if (orderDetails.value.order.deliveryMethod === 'LOGISTICS') {
          getOrderPackage(orderDetails.value.order.sn);
          traces();
        }
      }
    });
  };
  // 订单超时已取消
  const onFinish = () => {};
  // 查看物流
  const logisticsList = () => {
    data.value.logisticsModal = true;
    data.value.packageTraceList = data.value.orderPackage;
  };
  // 取消订单
  const handleCancelOrder = (sn: any) => {
    data.value.cancelParams.tradeSn = sn;
    afterSaleReason("CANCEL").then((res) => {
      if (res.data.success) {
        data.value.cancelReason = res.data.result;
        data.value.cancelAvail = true;
        data.value.cancelParams.reason = data.value.cancelReason[0].reason;
      }
    });
  };
  // 取消订单确认
  const sureCancel = () => {
    // 确定取消
    cancelOrder(data.value.cancelParams).then((res) => {
      if (res.data.success) {
        Message.success("取消订单成功");
        getDetail();
        data.value.cancelAvail = false;
      }
    });
  };
  // 去支付
  const goPay = (sn: any) => {
    router.push({path: '/payment/payment', query: {orderType: 'TRADE', sn}});
  };
  // 确认收货
  const received = (sn: any) => {
    Modal.confirm({
      title: '确认收货',
      content: `当前订单是否确认收到货物？`,
      okButtonProps: {
        type: "primary",
        status: "danger"
      },
      onOk: () => {
        sureReceived(sn).then(res => {
          if (res.data.success) {
            Message.success('确认收货成功');
            getDetail();
          }
        })
      }
    })

  };
  // 跳转店铺首页
  const goShopPage = (id: any) => {
    let routeUrl = router.resolve({path: "/merchant", query: { id },});
    window.open(routeUrl.href, "_blank");
  };
  // 跳转商品详情
  const goodsDetail = (skuId: any, goodsId: any) => {
    let routeUrl = router.resolve({path: "/goodsDetail", query: { skuId, goodsId },});
    window.open(routeUrl.href, "_blank");
  };

  // 申请售后
  const applyAfterSale = (sn: any) => {
    router.push({path: '/user/home/orderCenter/applyAfterSale', query: { sn }})
  };
  // 评价
  const comment = (sn: any, goodsIndex: any) => {
    router.push({path: '/user/home/memberCenter/addComment', query: { sn, index: goodsIndex }})
  };
  // 投诉
  const complain = (sn: any, goodsIndex: any) => {
    router.push({path: '/user/home/memberCenter/complain', query: { sn, index: goodsIndex }})
  };


  onMounted(() => {
    getDetail();
  })
</script>

<style scoped lang="less">
  .verificationCode {
    font-size: 20px;
    margin-bottom: 20px;
    color: rgb(65, 63, 63);
    font-weight: bold;
    text-align: center;
    span {
      color: @theme_color;
    }
  }

  :deep(.arco-steps-vertical .arco-steps-item:not(:last-child)) {
    min-height: 60px;
  }
  :deep(.arco-steps-item-finish .arco-steps-icon) {
    color: @theme_color;
  }
  :deep(.arco-steps-item:not(:last-child).arco-steps-item-finish .arco-steps-item-tail::after) {
    background-color: @theme_color;
  }

  .order-card {
    border-bottom: 1px solid @border_color;
    h3 {
      margin: 8px 0;
      font-weight: normal;
    }
    p {
      margin: 6px 0;
    }
  }


  .layui-layer-wrap {
    .flex {
      height: 32px;
      color: @text_color;
      line-height: 32px;
      > div:nth-of-type(1) {
        width: 80px;
      }
    }
    > .div-express-log {
      max-height: 300px;
    }
    :deep(.div-express-log::-webkit-scrollbar) {
      width: 1px;
      height: 5px;
    }
    :deep(.div-express-log::-webkit-scrollbar-thumb) {
      border-radius: 1em;
      background-color: rgba(50,50,50,.3);
    }
    :deep(.div-express-log::-webkit-scrollbar-track) {
      border-radius: 1em;
      background-color: rgba(50,50,50,.1);
    }
  }
  .div-express-log {
    border: solid 1px #e7e7e7;
    background: #fafafa;
    overflow-y: auto;
    overflow-x: auto;
  }
  .express-log {
    padding: 0 10px;
    list-style-type: none;
    .time {
      width: 30%;
      display: inline-block;
      float: left;
    }
    .detail {
      width: 60%;
      margin-left: 30px;
      display: inline-block;
    }
    li {
      line-height: 30px;
    }
  }
  .express-log-name {
    li {
      display: flex;
      span  {
        display: flex;
      }
    }
  }

  .goods {
    color: @light_text_color;
    .shop-name {
      color: @primary_color;
    }
    .shop-name:hover {
      color: @link_color;
    }
    .goods-header {
      height: 36px;
      align-items: center;
      text-align: center;
      padding: 0 10px;
    }
    .goods-body {
      align-items: center;
      border: 1px solid @border_color;
      border-top: none;
      text-align: center;
      padding: 10px;
      font-size: 14px;
      .goods-detail {
        align-items: center;
      }
    }
  }
  .order-price {
    color: @light_text_color;
    text-align: right;
    font-size: 15px;
    > div {
      height: 30px;
      line-height: 30px;
    }
    > div > span:nth-child(2) {
      width: 130px;
      text-align: right;
      display: inline-block;
    }
    .actrual-price {
      color: @theme_color;
      font-weight: bold;
      font-size: 18px;
    }
  }
</style>
